package com.linjiang;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class NIOServer {

    private static List<SocketChannel> list = new ArrayList<>();

    public static void main(String[] args) throws IOException {
        //创建 NIO ServerSocketChannel
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.socket().bind(new InetSocketAddress(8081));
        //设置为非阻塞
        serverSocketChannel.configureBlocking(false);
        System.out.println("nio启动成功");
        while (true){
            //非阻塞模式accept方法不会阻塞，否则会阻塞
            //NIO的非阻塞是由操作系统内部实现的，底层调用了linux内核的accept函数
            SocketChannel socketChannel = serverSocketChannel.accept();
            if (socketChannel != null){
                System.out.println("连接成功");
                //设置socketChannel为非阻塞
                socketChannel.configureBlocking(false);
                //将客户端连接放入list
                list.add(socketChannel);
            }

            //遍历socket 看是否有数据可读取
            Iterator<SocketChannel> iterator = list.iterator();
            while (iterator.hasNext()){
                SocketChannel sc = iterator.next();
                ByteBuffer byteBuffer = ByteBuffer.allocate(1);
                int read = sc.read(byteBuffer);
                if (read > 0){
                    System.out.println("接收到数据："+new String(byteBuffer.array()));
                }else if (read == -1){
                    //如果客户端断开，把socket从集合中去掉
                    iterator.remove();
                    System.out.println("客户端断开连接");
                }
            }
        }
    }

}
